<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>本地存储</title>
    <style>
        table {
            font-family: Arial, sans-serif;
            border-collapse: collapse;
            width: 100%;
        }
    
        th, td {
            border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;
        }
    
        tr:nth-child(even) {
            background-color: #f2f2f2;
        }
    
        th {
            background-color: #4CAF50;
            color: white;
        }
    </style>
    
</head>

<body>
    <label>姓名:</label><input type="text" id="name" value="">
    <label>年龄:</label><input type="text" id="age" value="">
    <label>性别:</label><input type="text" id="gender" value="">
    <input type="submit" onclick="AddStu()" value="添加">

    <table>
        <thead>
            <tr>
                <td>姓名</td>
                <td>年龄</td>
                <td>性别</td>
            </tr>
        </thead>
        <tbody id="tbody">

        </tbody>
    </table>
    <script>
        let name = document.getElementById('name');
        let age = document.getElementById('age');
        let gender = document.getElementById('gender');
        let tbody = document.getElementById('tbody');
        let student = [];
        tbody.innerHTML = '';
        let stu = localStorage.getItem('student');
        if (stu){
            stu = JSON.parse(stu);
            student = stu;
            for (let i = 0; i < stu.length; i++) {
                box = `<tr><td>${stu[i].name}</td><td>${stu[i].age}</td><td>${stu[i].gender}</td></tr>`;
                tbody.innerHTML += box;
            }
        }else{

        }

        function AddStu() {
            let stu_dict = {
                name: name.value,
                age: age.value,
                gender: gender.value
            }
            box = `<tr><td>${name.value}</td><td>${age.value}</td><td>${gender.value}</td></tr>`;
            tbody.innerHTML += box;
            student.push(stu_dict)
            console.log(student);
            localStorage += localStorage.setItem('student',JSON.stringify(student))
        }
    </script>
</body>

</html>